# -*- coding: utf-8 -*-
# @Time   : 2024-05-20 14:38
# @Author : 大龙 🚀

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode


class GxGxsbsstyqrmzf8E33Policy(BaseTaxPolicySpider):
    name = 'gx_gxsbsstyqrmzf_8e33_policy'

    province = "广西壮族自治区"
    city = "百色市"
    county = "田阳区"
    park = ""
    source = "广西省百色市田阳区人民政府"

    def start_requests(self):
        url = 'http://www.gxty.gov.cn/zfxxgk/jzxxgk/zfxxgkzl/fdzdgknr/zfwj/#%E5%85%B6%E4%BB%96%E6%96%87%E4%BB%B6'
        yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath('//div[@id="morelist"]//ul/li[not(@id)]//a[contains(@href, "htm") or @title]/ancestor::li[string-length(string(.))>=10]'):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.xpath("""//script""").re_first(r"""createPageHTML\((\d+),""")
            for page_num in range(1, int(total_page)):
                url = "http://www.gxty.gov.cn/zfxxgk/jzxxgk/zfxxgkzl/fdzdgknr/zfwj/#%E5%85%B6%E4%BB%96%E6%96%87%E4%BB%B6"
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline
    cmdline.execute("scrapy crawl gx_gxsbsstyqrmzf_8e33_policy".split())
